package com.express.service;

import com.express.bean.Express;
import com.express.dao.BaseExpressDao;
import com.express.dao.impl.ExpressDaoMysql;
import com.express.exception.DuplicateCodeException;
import com.express.util.RandomUtil;
import com.express.util.SMSUtil;

import java.util.List;
import java.util.Map;

/**
 * @Author: laixiangdong
 * @Date 2020/12/06
 */
public class ExpressService {

    private static BaseExpressDao dao = new ExpressDaoMysql();

    public static List<Map<String, Integer>> console() {
        return dao.console();
    }

    public static List<Express> findAll(boolean limit, int offset, int pageNumber) {
        return dao.findAll(limit, offset, pageNumber);
    }

    public static Express findByNumber(String number) {
        return dao.findByNumber(number);
    }

    public static Express findByCode(String code) {
        return dao.findByCode(code);
    }

    public static List<Express> findByUserPhone(String userPhone) {
        return dao.findByUserPhone(userPhone);
    }
    public static List<Express> findByUserPhoneAndStatus(String userPhone, int status) {
        return dao.findByUserPhoneAndStatus(userPhone,status);
    }

    public static List<Express> findBySysPhone(String sysPhone) {
        return dao.findBySysPhone(sysPhone);
    }

    public static Boolean insert(Express express) {
        express.setCode(RandomUtil.getCode());
        try {
            Boolean flag = dao.insert(express);
            if (flag) {
                System.out.println("发短信-----" + express.getUserPhone() + "----" + express.getCode());
                // SMSUtil.sendExpressCode(express.getUserPhone(), express.getCode());
            }
            return flag;
        } catch (DuplicateCodeException e) {
            return insert(express);
        }
    }

    public static Boolean update(int id, Express newExpress) {
        Express express = dao.findByID(id);
        if (newExpress.getUserPhone() != null && !newExpress.getUserPhone().equals(express.getUserPhone()) || newExpress.getStatus() == 0 && express.getStatus() == 1) {
            dao.delete(id);
            express.setUserPhone(newExpress.getUserPhone());
            // 重新发短信
            insert(express);
            id = dao.findByNumber(express.getNumber()).getId();
        }
        if (newExpress.getStatus() == 1) {
            updateStatus(dao.findByID(id).getCode());
        }
        return dao.update(id, newExpress);
    }

    public static Boolean delete(int id) {
        return dao.delete(id);
    }

    public static Boolean updateStatus(String code) {
        return dao.updateStatus(code);
    }
}
